using Baula.Testing.Common;
using TechTalk.SpecFlow;
using TechTalk.SpecFlow.Assist;

namespace Baula.TextGen.ActiveTemplating.Specs.StepDefinitions
{
    [Binding]
    public class CommonStepDefinitions
    {
        private Engine _engine;
        private string _template;
        private string _result;

        [Given(@"the default context is")]
        public void GivenTheDefaultContextIs(Table table)
        {
            var defaultContext = table.CreateInstance<DefaultContext>();
            ScenarioContext.Current.Set(defaultContext);
        }

        [Given(@"I have the template ""(.*)""")]
        [Given(@"I have the template")]
        public void GivenIHaveTheTemplate(string template)
        {
            _template = template;
        }

        [When(@"I insert that template")]
        public void WhenIInsertThatTemplate()
        {
            var defaultContext = ScenarioContext.Current.Get<DefaultContext>();
            var formsContext = ScenarioContext.Current.GetOrDefault<FormsContext>() ?? new FormsContext();
            var tablesContext = ScenarioContext.Current.GetOrDefault<TablesContext>() ?? new TablesContext();
            var context = new Context(defaultContext, formsContext, tablesContext);
            var executor = new Executor(context);
            executor.Listener = new ExecutionListener();
            _engine = new Engine(new TemplateToVBConverter(), executor, new DefaultContextMapping());
            _result = _engine.Process(_template);
        }

        [Then(@"the result should be")]
        [Then(@"the result should be ""(.*)""")]
        public void ThenTheResultShouldBe(string expectedResult)
        {
            _result.AssertEqualsIgnoringTrailingNewLine(expectedResult);
        }
    }
}